package com.tian.common.config;

import com.tian.mq.producer.DelayDeleteCacheProducer;
import org.redisson.api.RedissonClient;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Calendar;
import java.util.Date;

/**
 * {@code @description:} TODO
 *
 * @author tianwc 公众号：Java后端技术全栈
 * 在线刷题 1200+java面试题和1000+篇技术文章：<a href="https://woaijava.cc/">博客地址</a>
 * {@code @date:} 2025-02-20 11:04
 * {@code @version:} 1.0
 */
@Component
public class DelayDeleteCache {
    @Resource
    private ThreadPoolTaskScheduler threadPoolTaskScheduler;
    @Resource
    private RedissonClient redissonClient;
    @Resource
    private DelayDeleteCacheProducer delayDeleteCacheProducer;

    /**
     * 延迟删除redis缓存
     *
     * @param key                redis缓存key
     * @param delayMillisSeconds 延迟时间,单位毫秒 ,默认1000毫秒
     */
    public void delayDelete(String key, int delayMillisSeconds) {
        if (delayMillisSeconds <= 0) {
            //默认1000毫秒
            delayMillisSeconds = 1000;
        }
        Date add = add(new Date(), delayMillisSeconds);
        DeleteCacheTask task = new DeleteCacheTask(redissonClient, key, delayDeleteCacheProducer);
        threadPoolTaskScheduler.schedule(task, add);
    }

    public static Date add(Date date, int delayMillisSeconds) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.MILLISECOND, delayMillisSeconds);
        return calendar.getTime();
    }
}
